const mongoose = require("mongoose");

const ueInstanceSchema = new mongoose.Schema(
  {
    // 基本信息
    name: {
      type: String,
      required: true,
      trim: true,
    },
    projectId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: "Upload", // 关联到上传的UE工程
      validate: {
        // 添加验证确保Upload存在
        validator: async function (value) {
          const Upload = mongoose.model("Upload");
          const upload = await Upload.findById(value);
          return upload !== null;
        },
        message: "关联的UE工程不存在",
      },
    },
    port: {
      type: Number,
      required: true,
    },
    ipAddress: {
      type: String,
      required: true,
      trim: true,
    },

    // 运行状态
    status: {
      type: String,
      default: "stopped",
      enum: [
        "stopped",
        "stopping",
        "running",
        "starting",
        "error",
        "deleting",
        "restarting",
      ],
    },
    isConnected: {
      type: Boolean,
      default: false,
    },

    // 运行时间统计
    startTime: {
      type: Date,
      default: null,
    },
    totalRuntime: {
      type: Number, // 以秒为单位
      default: 0,
    },

    // 分辨率配置
    useDefaultResolution: {
      type: Boolean,
      default: true,
    },
    resolutionX: {
      type: Number,
      default: 1920,
    },
    resolutionY: {
      type: Number,
      default: 1080,
    },

    // HTTPS和中继服务器配置
    useHTTPS: {
      type: Boolean,
      default: false,
    },
    useRelay: {
      type: Boolean,
      default: false,
    },
    gpuId: {
      type: Number,
      default: 0,
    },
    signalStatus: {
      type: String,
      default: "pending",
      enum: ["pending", "success", "failed"],
    },
    signalPath: {
      type: String,
      default: "",
    },
    signalHost: {
      type: String,
      default: "",
    },
    signalPort: {
      type: Number,
      default: 0,
    },
    clientIp: {
      type: String,
      default: "",
    },
  },
  {
    timestamps: true, // 添加 createdAt 和 updatedAt 字段
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);
ueInstanceSchema.virtual("project", {
  ref: "Upload",
  localField: "projectId",
  foreignField: "_id",
  justOne: true,
});
// 添加索引以优化查询性能
ueInstanceSchema.index({ projectId: 1 });
ueInstanceSchema.index({ isRunning: 1 });

const UEInstance = mongoose.model("UEInstance", ueInstanceSchema);

module.exports = UEInstance;
